<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Constants\ErrorCode;
use App\Model\Admin\Admin;
use Hyperf\Redis\Redis;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\InvalidArgumentException;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use Util\Common;
use Phper666\JWTAuth\JWT;
use Phper666\JWTAuth\Util\JWTUtil;
use App\Services\Wechat;
use App\Controller\AbstractController;


class AdminController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;
    protected JWT $jwt;
    protected Wechat $wechat;

    #[Inject]
    protected Admin $admin;

    public function __construct()
    {
        $this->jwt = container()->get(JWT::class);
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
        $this->wechat = container()->get(Wechat::class);
    }

    /**
     * 后台登录 with jwt
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws RedisException|InvalidArgumentException
     */
    public function login(RequestInterface $request): ResponseInterface
    {
        $credentials = $request->inputs(['username', 'password']);
        $info = $this->admin->where('mobile','=' ,$credentials['username'])
            ->first();
        if (empty($info)) {
            return $this->error(ErrorCode::UNKNOW_EMAIL);
        }
        if(!password_verify($credentials['password'],$info->password)){
            return $this->error(ErrorCode::PASS_ERR);
        }
        $info = $this->admin->makeInfo($info);
        $token = $this->jwt->getToken('admin', $info);
        $stringToken = $token->toString();
        $this->jwt->getTTL($stringToken);
        $this->redis->setex(Common::USER_REDIS_INFO . $info['id'], $this->jwt->getTTL($stringToken) + 30, json_encode($info));
        return $this->success(['token' => $stringToken]);
    }

    /**
     * 检测登录状态
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface|RedisException
     */
    public function getInfo(RequestInterface $request): ResponseInterface
    {
        $data = $this->admin->getInfo($request);
        if ($data) {
            return $this->success($data);
        }
        return $this->error(ErrorCode::UNKNOW_INFO);
    }

    /**退出登录
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws InvalidArgumentException
     * @throws NotFoundExceptionInterface
     */
    public function logout(RequestInterface $request): ResponseInterface
    {
        $token = $request->getHeaderLine('Token');
        $this->jwt->logout($token);
        return $this->success(msg: '退出成功');
    }


    /**管理员列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function adminList(RequestInterface $request):ResponseInterface
    {
        $info = $this->admin->getInfo($request);
        if ($info['type'] != Admin::TYPE_ADMIN) {
            return $this->error(1001,'权限不足');
        }
        try {
            $page = $request->inputs(['page', 'limit', 'mobile', 'keyword', 'type']);
            $query = $this->admin->query();
            if (isset($page['keyword']) && $page['keyword']) {
                $query->where('name', 'like', '%' . $page['keyword'] . '%');
            }

            if (isset($page['type']) && $page['type']) {
                $query->where('type', $page['type']);
            }

            if (isset($page['mobile']) && $page['mobile']) {
                $query->where('mobile', $page['mobile']);
            }
            $data['total'] = $query->count();
            $data['list'] = $query->orderBy('id', 'desc')
                ->offset(($page['page'] - 1) * $page['limit'])
                ->limit($page['limit'])
                ->get();
            return $this->success($data);
        } catch (\Exception $e) {
            return $this->error();
        }
    }


    /**创建编辑管理员
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function create(RequestInterface $request):ResponseInterface
    {
        $info = $this->admin->getInfo($request);
        if ($info['type'] != Admin::TYPE_ADMIN) {
            return $this->error(1001,'权限不足');
        }
        $data = $request->post();
        if(!$data['mobile']){
            return $this->error(1001,'请填写手机号');
        }
        if(!$data['name']){
            return $this->error(1001,'请填写姓名');
        }
        if (strlen($data['password'])>30 || strlen($data['password'])<6)
        {
            $this->error(1001, '密码必须为6-30位的字符串');
        }
        $model = new Admin();
        $model->fill($data);
        $model->password = password_hash($data['password'], PASSWORD_DEFAULT);
        $model->save();
        return $this->success();
    }

    /**
     * 更新管理员信息
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function update(RequestInterface $request): ResponseInterface
    {
        $info = $this->admin->getInfo($request);
        if ($info['type'] != Admin::TYPE_ADMIN) {
            return $this->error(1001,'权限不足');
        }
        $data = $request->post();
        $id = $request->input('id', 0, 'int');
        if (!$id) {
            return $this->error(1003, '缺少参数id');
        }

        if (!$data['mobile']) {
            return $this->error(1001, '请填写手机号');
        }

        if (!$data['name']) {
            return $this->error(1001, '请填写姓名');
        }
        // 检查密码是否被修改
        if (!empty($data['password'])) {
            if (strlen($data['password']) < 6 || strlen($data['password']) > 30) {
                return $this->error(1001, '密码必须为6-30位的字符串');
            }
            $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
        } else {
            unset($data['password']); // 不更新密码字段
        }
        // 找到管理员模型
        $admin = $this->admin->where('id', $id)->first();
        if (!$admin) {
            return $this->error(ErrorCode::UNKNOW_INFO);
        }
        // 填充并保存数据
        $admin->fill($data);
        $admin->save();
        return $this->success(msg: '更新成功');
    }





    /**删除管理员
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function del(RequestInterface $request):ResponseInterface
    {
        $info = $this->admin->getInfo($request);
        if ($info['type'] != Admin::TYPE_ADMIN) {
            return $this->error(1001,'权限不足');
        }
        $id = $request->input('id',0,'int');
        if (!$id) {
            return $this->error(1003,'缺少参数id');
        }
        $this->admin->where('id',$id)->delete();
        return $this->success(msg:'删除成功');
    }
}
